const {File} = require('spring-ioc')
const path = require('path');
const moment = require('moment');

//@Bean
class AppLog {

	//@SpringFactory
	factory;

	logDirectory;

	beanInit(){

		//日志目录
		this.logDirectory = path.join(this.factory.args.rootPath,'log');

	}

	getFile(fsPath){
		return new File(path.join(this.logDirectory,fsPath))
	}

}

/**
	系统生命周期日志
	记录系统运行的数据
*/
//@Bean
class LifeCircleService {

	//@Autowired
	appLog;

	//日志文件
	file;

	//日志内容
	data;

	//初始化bean 加载日志
	beanInit(){
		this.file = this.appLog.getFile('lifeCircle.log')
		if(!this.file.exist()){
			this.file.touch();
			this.update({
				lastOrderStamp:0,
				totalAmount:0,
				totalCount:0,
				price:{},
				balance:0,
				marketSentiment:50,
				totalSellAmount:0
			}).flush();
		}else{
			this.data = this.file.getObject();
		}
	}


	update(data){
		this.data = {...this.data,...data}
		return this;
	}

	flush(){
		this.file.setObject(this.data).write();
		return this;
	}

	//获取最后订单
	getLastOrderTime(){
		return this.data.lastOrderStamp;
	}

	//更新最后订单时间
	updateLastOrderTime(){
		this.update({lastOrderStamp:moment().valueOf(),lastOrderDate:moment().format('YYYY-MM-DD HH:mm:ss')}).flush();
	}

	//增加定投金额控制
	addAmount(amount,price,balance){
		const updateData = {
			totalAmount:this.data.totalAmount+amount,
			balance,
			totalCount:this.data.totalCount+1,
			price:{...this.data.price,...price}
		}

		this.update(updateData).flush();
	}

	//增加累计出售金额
	addSellAmount(sellAmount){
		this.update({totalSellAmount:this.data.totalSellAmount+sellAmount}).flush();
	}

	//写入启动信息
	startInfo(buyInterval){
		this.update({systemStartDate:moment().format('YYYY-MM-DD HH:mm'),msg:"系统启动日常",buyInterval:(buyInterval/1000/60/60).toFixed(2)+"小时"}).flush()
	}

	//更新市场情绪
	updateMarketSentiment(value){
		this.update({marketSentiment:value}).flush();
	}

	//获取市场情绪值
	getSentiment(){
		return this.data.marketSentiment;
	}
}

/**
	交易日志系统，记录交易信息。
*/
//@Bean
class TxLogService  {

	//@Autowired
	appLog;

	getLogFile(){
		const time = moment().format("YYYY-MM");
		return this.appLog.getFile(`tx-${time}.log`);
	}

	//下单成功
	orderSuccess(data){
		data.date = moment().format("YYYY-MM-DD HH:mm:ss")
		this.appendJson(data)
	}

	appendJson(data){
		this.getLogFile().append(JSON.stringify(data)+"\n");
	}

}


/**
	系统日志 专门存储一些错误信息
*/
//@Bean
class SystemLogService extends TxLogService {

	//@Autowired
	appLog;

	//@Autowired
	lifeCircleService;

	//@Autowired
	emailService;

	async operateError(errorMsg,resetOrderSteamp=false){
		
		if(resetOrderSteamp){
			//日志:更新订单时间戳 防止在心跳内重复提醒
			this.lifeCircleService.update({lastOrderStamp:moment().valueOf(),msg:errorMsg}).flush();
		}

		//日志:记录错误信息到日志
		this.appendJson({state:"error",msg:errorMsg});
		//邮件:发送错误信息到邮件
		await this.emailService.error(errorMsg);
	}

	getLogFile(){
		return this.appLog.getFile(`system.log`);
	}

}

module.exports = { LifeCircleService,AppLog,TxLogService,SystemLogService }